import { pushLayer, popLayer, clearLayer } from '../actions';
import { fetchStart, fetchEnd } from '../actions/util';
import { createReducer } from './util';

import * as devTeamReducers from './dev-team';
import * as userReducers from './user';
import * as runnableGroupReducers from './runnable-group';
import * as runnableUnitReducers from './runnable-unit';
import * as machineReducers from './machine';
import * as serviceReducers from './service';
import * as environmentReducers from './environment';
import * as companyReducers from './company';
import * as roleReducers from './role';
import * as builderReducers from './builder';
import * as logReducers from './log';

import _ from 'lodash';
import { combineReducers } from 'redux';
import updateHelper from 'react-addons-update';

const layers = createReducer(on => {
  on(pushLayer)
    .completed((state, action) => updateHelper(state, { $push: [action.payload] }));
  on(popLayer)
    .completed((state) => {
      return state.length > 0 ? updateHelper(state, { $splice: [[-1, 1]] }) : state;
    });
  on(clearLayer)
    .completed(() => []);
}, []);

const fetchStatus = createReducer(on => {
  on(fetchStart)
    .completed((state, action) => {
      const { type, key } = action.payload;

      if (key !== undefined) {
        const old = _.isObject(state[type]) ? state[type] : {};
        return Object.assign({}, state, {
          [type]: Object.assign({}, old, { [key]: true })
        });
      }
      return Object.assign({}, state, { [type]: true });
    });
  on(fetchEnd)
    .completed((state, action) => {
      const { type, key } = action.payload;

      if (key !== undefined) {
        const old = _.isObject(state[type]) ? state[type] : {};
        return Object.assign({}, state, {
          [type]: _.omit(old, key)
        });
      }
      return _.omit(state, type);
    });
}, {});

export default combineReducers({
  fetchStatus,
  layers,
  ...devTeamReducers,
  ...userReducers,
  ...runnableGroupReducers,
  ...runnableUnitReducers,
  ...machineReducers,
  ...serviceReducers,
  ...environmentReducers,
  ...companyReducers,
  ...roleReducers,
  ...builderReducers,
  ...logReducers
});
